﻿using ServerBase.LunarSocket;
using ServerBase.Protocol;
using ServerBase.Service;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerBase.Client
{
    public static class LunarClientDispatcher
    {
        //绑定列表
        public static Dictionary<EProtocolId, Func<short>> DictProtocolEvent
            = new Dictionary<EProtocolId, Func<short>>();
        //绑定注册
        public static void BindEventHandler(Func<short> action, EProtocolId id)
        {
            DictProtocolEvent[id] = action;
            LunarClientDebug.Debug(string.Format("注册消息->  {0,-30} -> {1,-10} -> {2} 成功", id, (int)id, action.Method));
        }

        public class ClientMessageInfo
        {
            public int LinkId;
            public byte[] Buffer;
            public ClientMessageInfo(int linkid, byte[] buffer)
            {
                LinkId = linkid;
                Buffer = buffer;
            }
        }
        //消息队列
        public static ConcurrentQueue<LunarRequestInfo> ListMsg = new ConcurrentQueue<LunarRequestInfo>();
        //消息处理
        public static void OnReceiveData(LunarRequestInfo msg)
        {
            ListMsg.Enqueue(msg);
        }

        //消息处理
        public static void OnDispatcher()
        {
            while (ListMsg.TryDequeue(out var msg))
            {
                ProcessMessage(msg);
            }
        }

        public static LunarRequestInfo OnMsg;
        //当前正在处理的协议ID
        public static EProtocolId OnPId;

        // 处理消息
        public static void ProcessMessage(LunarRequestInfo msg)
        {
            OnMsg = msg;
            EProtocolId id = OnMsg.ProtocolID;

            LunarClientDebug.Debug(string.Format("处理协议->  {0} -> {1} ......", id, (int)id));

            if (!DictProtocolEvent.TryGetValue(id, out var action))
            {
                LunarClientDebug.Debug(string.Format("未注册协议->  {0} -> {1} ......", id, (int)id));
                return;
            }
            try
            {
                //设置正在处理
                OnPId = id;
                //处理
                action();
            }
            catch (Exception ex)
            {
                LunarClientDebug.Error(string.Format("处理协议->  {0} -> {1}出错 ex:{2}", id, (int)id, ex.Message));
            }
        }

    }
}
